// 登陆的统一方法
import { mapGetters } from "vuex";
import { setStore, getStore } from "@/util/store.js";
import { setTheme, encryption } from "@/util/util.js";
import { loginByUsername, getTgUserRole } from "@/api/login/login.js";
import { postDefaultSystem, getProject } from "@/api/desktop/index.js";
import { getBySystemId } from "@/api/admin/user";
// import { getProject} from "@/api/desktop/index.js";
const columnNum = 4;

export default {
  name: "defaultLogin",
  data() {
    return {
      isLogin: false,
      // 用户账号密码
      loginForm: {
        username: "",
        password: "",
        code: "",
        redomStr: Number(new Date())
      },
      acountAct: false,
      passwordAct: false,
      rememberInfo: false,
      data: {},
      token: ""
    };
  },
  computed: {
    ...mapGetters(["themeName", "tagWel", "systemCode", "systemInfo"])
  },
  created() {
    // 设置主题跟用户账号密码
    setTheme(this.themeName);
    this.fn_getNameAndPwd();
  },
  mounted() {
    this.$refs.userName && this.$refs.userName.focus();
  },
  methods: {
    getBySystemIdFun(params) {
      return new Promise(resolve => {
        getBySystemId(params).then(res => {
          // console.log(res);
          resolve(res.data.data);
        });
      });
    },
    getProjectFun() {
      return new Promise(resolve => {
        getProject().then(res => {
          let data = res.data;
          if (data.code === 0) {
            console.log(data.data);
            this.$store.commit("SET_PROJECT", data.data);
            // this.$store.commit("SET_PROJECTINFO", data.data.projectNo);
            resolve(data.data);
          }
        });
      });
    },
    changeListData(data) {
      let target = [];
      for (var i = 0; i < data.length; i += columnNum) {
        target.push({
          name: Math.random(),
          children: data.slice(i, i + columnNum)
        });
      }
      return target;
    },
    // 登录获取token
    loginByUsernameFun(user) {
      return new Promise((resolve, reject) => {
        loginByUsername(
          user.username,
          user.password,
          user.code,
          user.redomStr
        ).then(res => {
          if (res.data.access_token) {
            // this.$store.commit("SET_ACCESS_TOKEN", res.data.access_token);
            // this.$store.commit("SET_REFRESH_TOKEN", res.data.refresh_token);
            // this.$store.commit("SET_EXPIRES_IN", res.data.expires_in);
            // this.$store.commit("CLEAR_LOCK");
            // // 如果勾选了保持记住密码，则设置账号密码到本地
            // setStore({ name: "rememberInfo", content: this.rememberInfo });
            // if (this.rememberInfo) {
            //   setStore({
            //     name: "userName",
            //     content: this.loginForm.username
            //   });
            //   setStore({
            //     name: "password",
            //     content: this.loginForm.password
            //   });
            // }
            this.isLogin = false;
            resolve(res.data);
            // 获取用户信息的数据
            // this.$store.dispatch("GetUserInfo").then(data => {
            //   console.log(data);
            //   // this.isLogin = false;
            //   // this.$router.push({ path: "/" });
            // });
          }
        });
      });
    },
    // 判断用户权限
    getTgUserRoleFun(no, access_token) {
      return new Promise((resolve, reject) => {
        getTgUserRole(no, access_token).then(res => {
          console.log(res);
          resolve(res.data);
        });
      });
    },
    // 登录
    async loginIn() {
      this.isLogin = true;
      const user = encryption({
        data: this.loginForm,
        key: "gdprgdprgdprgdpr",
        param: ["password"]
      });
      let data = await this.loginByUsernameFun(user);
      this.$store.commit("SET_CURRENTUSER", data);
      // console.log(this.systemCode);
      let code = this.systemInfo.productCode;
      console.log(data);
      this.token = data.access_token;
      // console.log(data.access_token);
      let roleData = await this.getTgUserRoleFun(code, data.access_token);
      console.log(roleData);

      if (!roleData.data || roleData.data.length === 0) {
        this.$message({
          message: "该账号没有权限!",
          type: "error"
        });
      } else {
        if (Array.isArray(roleData.data) && roleData.data.length === 1) {
          let targetData = roleData.data[0];
          let params = {
            name: targetData.name,
            value: targetData.menuId
          };
          postDefaultSystem(params, this.token).then(res => {
            if (res.data.code === 0) {
              console.log(res.data.data);
              this.goToHome(data, res.data.data.id);
              this.$store.commit("SET_NEED_MENBER", false);
            }
          });
        } else if (Array.isArray(roleData.data) && roleData.data.length > 1) {
          console.log(roleData.data);
          this.$store.commit("SET_NEED_MENBER", true);
          this.$nextTick(() => {
            if (this.$refs.choseMenber) {
              let changeData = this.changeListData(roleData.data);
              console.log(changeData);
              this.$refs.choseMenber.setMenberData(changeData);
            }
          });
        }
      }
    },
    async goToHome(data, type) {
      this.setBaseInfo(data);
      let code = this.systemInfo.productCode;
      let params = {
        productCode: code
      };
      await this.$store.dispatch("GetUserInfo", params);
      await this.getProjectFun();
      let layoutData = await this.getBySystemIdFun({
        systemId: type
      });
      this.$store.commit("SET_LAYOUT", layoutData);
      // await this.$store.dispatch("GetMenu", type);
      this.$router.push({ path: "/" });
    },
    // 设置基础信息
    setBaseInfo(data) {
      this.$store.commit("SET_ACCESS_TOKEN", data.access_token);
      this.$store.commit("SET_REFRESH_TOKEN", data.refresh_token);
      this.$store.commit("SET_EXPIRES_IN", data.expires_in);
      this.$store.commit("CLEAR_LOCK");
      // 如果勾选了保持记住密码，则设置账号密码到本地
      setStore({ name: "rememberInfo", content: this.rememberInfo });
      if (this.rememberInfo) {
        setStore({
          name: "userName",
          content: this.loginForm.username
        });
        setStore({
          name: "password",
          content: this.loginForm.password
        });
      }
    },
    // 初始化账号密码
    fn_getNameAndPwd() {
      this.rememberInfo = getStore({ name: "rememberInfo" }) || false;
      if (this.rememberInfo) {
        this.loginForm.username = getStore({ name: "userName" }) || "admin";
        this.loginForm.password = getStore({ name: "password" }) || "123456";
      }
    },

    // 记住我
    handleRemenber() {
      console.log("");
    },

    // 重置
    handleReset() {
      this.loginForm.username = "";
      this.loginForm.password = "";
      this.$refs.userName && this.$refs.userName.focus();
    }
  }
};
